import SwiftUI

struct NetSpeedView: View {
    @EnvironmentObject var viewModel: SpeedViewModel
    @EnvironmentObject var timerModel: TimerViewModel
    @State private var speedDisplay: String = "--"
    @State private var carrierName: String? = nil
    @Environment(\.presentationMode) var presentationMode
    @State private var progress: Double = 0
    @State private var upload = "Upload"
    @State private var download = "Download"
    @State private var isHighlighted: Bool = false
    @State private var isWifi = false
    @State private var isDevice = false
    @StateObject private var infoModel = IPInfoViewModel()
    var body: some View {
        NavigationView {
            ZStack {
                MainView()
                VStack {
                    Back(title: "Speed Test", onBackTap: {
                        self.presentationMode.wrappedValue.dismiss()
                    }, onImageTap: {})
                    HStack {
                        
                        VStack {
                            
                            HStack {
                                HStack{
                                    
                                    Text(download)
                                        .frame(width: 100)
                                        .foregroundColor(.white)
                                        .padding(.all, 10)
                                        .background(isHighlighted ? Color("highlightedColor") : Color("alphaStart"))
                                        .cornerRadius(10)
                                        .onTapGesture {
                                            isHighlighted = false
                                            viewModel.startTest(isDownload: false)
                                        }
                                    
                                    Spacer()
                                    
                                    Text(upload)
                                        .frame(width: computeAndReturnCGFloat() / 2)
                                        .foregroundColor(.white)
                                        .padding(.all, 10)
                                        .background(isHighlighted ? Color("alphaStart") : Color("highlightedColor"))
                                        .cornerRadius(10)
                                        .onTapGesture {
                                            isHighlighted = true
                                            viewModel.startTest(isDownload: true)
                                        }
                                    
                                }.onAppear{
                                    viewModel.startTest(isDownload: true)
                                    
                                    let originalText = "Download"
                                    if let encryptedText = encryptDecryptText(inputText: originalText, shouldEncrypt: true) {
                                        if let decryptedText = encryptDecryptText(inputText: encryptedText, shouldEncrypt: false) {
                                            self.download = decryptedText
                                        }
                                    }
                                    
                                    let originalString = "Upload"
                                    if let encrypted = aesEncryptDecrypt(input: originalString, encrypt: true) {
                                        if let decrypted = aesEncryptDecrypt(input: encrypted, encrypt: false) {
                                            self.upload = decrypted
                                        }
                                    }
                                    
                                    
                                    
                                }
                            } .padding(.all,10)
                                .background(Color("sp"))
                                .cornerRadius(10)
                            
                            
                            
                            
                            SemiCircularProgressBar(progress:  calculatePercentage(value:viewModel.downloadSpeed ?? 0.0))
                                .frame(width: 220, height: 160)
                                .padding(.top,40)
                            
                            Text("\(String(format: "%.2f", viewModel.downloadSpeed)) Mbps")
                                .font(.title)
                                .foregroundColor(.white)
                                .padding(.top,-40)
                            
                            HStack{
                                Button(action: {
                                    isWifi.toggle()
                                }, label: {
                                    HStack(spacing: 10, content: {
                                        Image("sbxx")
                                        VStack(alignment: .leading, spacing: 5) {
                                            Text("WiFi")
                                                .font(.subheadline)
                                                .foregroundColor(Color(hex: "#34F4E2"))
                                            Text("Security")
                                                .font(.subheadline)
                                                .foregroundColor(Color(hex: "#34F4E2"))
                                        }
                                    })
                                })
                                
                                
                                Spacer()
                                Image("lv")
                                Spacer()
                                
                                
                                Button(action: {
                                    isDevice.toggle()
                                }, label: {
                                    
                                    HStack(spacing: 10, content: {
                                        
                                        Image("sbaq")
                                        VStack(alignment: .leading, content: {
                                            Text("Device")
                                                .font(.subheadline)
                                                .foregroundColor(Color(hex: "#30E0F7"))
                                            Text("Information")
                                                .font(.subheadline)
                                                .foregroundColor(Color(hex: "#30E0F7"))
                                        })
                                    })
                                })
                                
                            }
                            
                            
                            HStack{
                                Image("fl")
                                Spacer()
                                VStack(alignment:.leading){
                                    Text("America")
                                        .foregroundColor(.white)
                                    if let ipInfo = infoModel.ipInfo {
                                        
                                        Text(ipInfo.ip)
                                        .foregroundColor(.white)}else{
                                            Text("loading...")
                                                .foregroundColor(.white)
                                        }
                                    
                                }
                                Spacer()
                                VStack(alignment:.leading){
                                    Text("Duration")
                                        .foregroundColor(.white)
                                    Text(timerModel.timeString)
                                        .foregroundColor(.white)
                                }
                            }.padding()
                            
                                .background(Color("sp"))
                                .cornerRadius(20)
                                .padding(.top,30)
                            
                        }
                        
                        
                    }
                    .padding()
                    .padding(.horizontal)
                    
                    
                    NavigationLink(destination: DeviceView(), isActive: $isDevice) {
                        EmptyView()
                    }
                    .hidden()
                    
                    NavigationLink(destination: WifiInfoView(), isActive: $isWifi) {
                        EmptyView()
                    }
                    .hidden()
                    
                    
                    Spacer()
                }
                .onAppear {
                    // viewModel.startTest()
                    carrierName = getCarrierName()
                }
                .environmentObject(viewModel)
                .onDisappear {
                    viewModel.cancelTest()
                }
            }
            .onAppear{
                
            }
            .navigationBarHidden(true)
            .navigationBarBackButtonHidden(true)
            .navigationViewStyle(StackNavigationViewStyle())
        }
        .navigationBarHidden(true)
        .navigationBarBackButtonHidden(true)
        .navigationViewStyle(StackNavigationViewStyle())
    }
    
}

#Preview {
    NetSpeedView()
    
}

struct SemiCircularProgressBar: View {
    var progress: Double
    
    var body: some View {
        ZStack (alignment:.top){
            ZStack(alignment:.bottom){
                Image("can")
                Image("zh")
                    .rotationEffect(.degrees( mapToRange(value: progress)), anchor: UnitPoint(x: 0.5, y: 0.8155))
                    .animation(.easeInOut(duration: 1), value: mapToRange(value: progress))
                
                
            }
            
            SemiCircleShape()
            
                .stroke(
                    AngularGradient(gradient: Gradient(colors: [Color.gray]),
                                    center: .center,
                                    startAngle: .degrees(180),
                                    endAngle: .degrees(360)),
                    style: StrokeStyle(lineWidth: 20, lineCap: .round)
                )
                .rotationEffect(Angle(degrees: 0))
                .animation(.linear(duration: 1.0), value: 100)
                .opacity(0.6)
            
            
            
            SemiCircleShape()
                .trim(from: 0, to: CGFloat(min(self.progress, 1.0)))
                .stroke(
                    AngularGradient(gradient: Gradient(colors: [Color("alphaStart"), Color("alphaEnd")]),
                                    center: .center,
                                    startAngle: .degrees(180),
                                    endAngle: .degrees(computeAndReturnCGFloats())),
                    style: StrokeStyle(lineWidth: 20, lineCap: .round)
                )
                .rotationEffect(Angle(degrees: 0))
                .animation(.linear(duration: 1.0), value: progress)
        }
        .padding(20)
    }
}

struct SemiCircleShape: Shape {
    func path(in rect: CGRect) -> Path {
        var path = Path()
        path.addArc(center: CGPoint(x: rect.midX, y: rect.midY),
                    radius: rect.width / 2,
                    startAngle: .degrees(170),
                    endAngle: .degrees(10),
                    clockwise: false)
        return path
    }
}





extension Color {
    init(hex: String) {
        // 移除 # 字符
        let cleanedHex = hex.replacingOccurrences(of: "#", with: "")
        
        // 确保十六进制字符串的长度为 6 或 8（带有透明度）
        guard cleanedHex.count == 6 || cleanedHex.count == 8 else {
            self.init(red: 0, green: 0, blue: 0) // 默认黑色
            return
        }
        
        // 从十六进制字符串提取 RGB(A) 值
        var rgb: UInt64 = 0
        Scanner(string: cleanedHex).scanHexInt64(&rgb)
        
        let red, green, blue, alpha: Double
        if cleanedHex.count == 6 {
            red = Double((rgb >> 16) & 0xFF) / 255.0
            green = Double((rgb >> 8) & 0xFF) / 255.0
            blue = Double(rgb & 0xFF) / 255.0
            alpha = 1.0 // 默认不透明
        } else {
            red = Double((rgb >> 24) & 0xFF) / 255.0
            green = Double((rgb >> 16) & 0xFF) / 255.0
            blue = Double((rgb >> 8) & 0xFF) / 255.0
            alpha = Double(rgb & 0xFF) / 255.0
        }
        
        self.init(red: red, green: green, blue: blue, opacity: alpha)
    }
}
